using System;
using System.Data;
using System.Web.UI.WebControls;
using Framework.Library.Components.Modules;
using Framework.Library.Components.Security;
using Framework.Library.Utilities;
using Framework.Library;
using Framework.Library.Components.Commands;
using System.Collections;
using System.IO;
using Framework.Library.Components.Roles;

namespace Portal.Administrator.Modules
{
	public partial class ModuleDefinitionEdit : AuthenticatedControl
	{
        private ArrayList lstFile = new ArrayList();

		protected void Page_Load(object sender, EventArgs e)
		{
            if ((!CurrentUser.IsSuperAdmin && CommandController.IsSystemModule(AppEnv.CommandID())) || !CommandController.IsAvailableForUser(AppEnv.CommandID(), CurrentUser.UserID, Convert.ToInt32(AppEnv.PortalId())))
                Response.Redirect(AppEnv.ADMIN_CMD, true);
            if (!IsPostBack)
            {
                DataTable dtModules = ModuleController.GetModules();
                int ModuleID = Convert.ToInt32(LoadForDropDownList(dtModules));
                LoadForTreeView(ModuleID);

                lblCommandName.Text = AppEnv.CommandName();
                MiscUtility.FillIndex(dropControlOrder, 30, 1);
            }
		}

        protected override void OnPreRender(EventArgs e)
        { 
            LoadData();
        }

        private void LoadData()
        {
            if (txtID.Text != string.Empty)
            {
                ModuleControlInfo curControl = ModuleControlController.GetModuleControl(ConvertUtility.ToInt32(txtID.Text));
                if (curControl != null)
                {
                    chkControlType.DataSource = RoleController.GetRoles();
                    chkControlType.DataBind();
                    if (curControl == null) return;
                    txtControlName.Text = curControl.ControlName;
                    txtControlKey.Value = curControl.ControlKey;
                    MiscUtility.SelectItemFromList(dropPath, curControl.ControlPath);
                    txtControlIcon.Text = curControl.ControlIcon;
                    txtControlTitle.Text = curControl.ControlTitle;
                    txtControlDescription.Text = curControl.ControlDescription;
                    chkControlHeader.Checked = curControl.ControlHeader;
                    MiscUtility.SelectItemFromList(dropControlOrder, curControl.ControlOrder.ToString());
                    string[] roleList = curControl.ControlRole.Split("|".ToCharArray());
                    MiscUtility.SelectItemFromList(chkControlType, roleList);
                }
            }
        }

        private string LoadForDropDownList(DataTable dtModules)
        {            
            foreach (DataRow row in dtModules.Rows)
            {                
                ListItem rootItem = new ListItem(row["ModuleName"].ToString(), row["ModuleID"].ToString());
                rootItem.Attributes.Add("Level", "0");
                drgModules.Items.Add(rootItem);
            }
            drgModules.Items.Insert(0, new ListItem("Root", "0"));
            return drgModules.SelectedValue;
        }


        private void LoadForTreeView(int ModuleID)
        {
            string nodePath = "|";
            TreeNode focusNode = tvwControls.SelectedNode;
            if (focusNode != null)
            {
                while (true)
                {
                    if (focusNode.Parent == null) break;
                    else
                    {
                        focusNode = focusNode.Parent;
                        nodePath += focusNode.Value + "|";
                    }
                }
            }
            tvwControls.Nodes.Clear();
            DataTable dtControls = ModuleControlController.GetModuleControls(ModuleID);
            if (dtControls.Rows.Count > 0)
            {
                TreeNode topRoot = new TreeNode();
                topRoot.Text = "Root";
                topRoot.Value = "0";
                tvwControls.Nodes.Add(topRoot);

                foreach (DataRow rows in dtControls.Rows)
                {
                    TreeNode rootNode = new TreeNode();
                    rootNode.Text = rows["ControlName"].ToString();
                    rootNode.Value = rows["ControlID"].ToString();
                    rootNode.Expanded = false;
                    tvwControls.Nodes.Add(rootNode);
                }
            }
        }
        protected void tvwControls_SelectedNodeChanged(object sender, EventArgs e)
        {
            txtID.Text = tvwControls.SelectedNode.Value;
            lblUpdateStatus.Text = string.Empty;
        }

        protected void btnCreate_Click(object sender, EventArgs e)
        {            
            string new_cmd = MiscUtility.CreateCommand();
            while (ModuleControlController.CheckExistsControlKey(new_cmd))
            {
                new_cmd = MiscUtility.CreateCommand();
            }
            ModuleControlInfo moduleControl = new ModuleControlInfo();
            moduleControl.ModuleID = Convert.ToInt32(drgModules.SelectedValue);
            moduleControl.ControlName = txtControlName.Text.Trim();
            moduleControl.ControlKey = new_cmd;
            moduleControl.ControlPath = dropPath.SelectedValue;
            moduleControl.ControlIcon = txtControlIcon.Text.Trim();
            moduleControl.ControlOrder = ConvertUtility.ToInt32(dropControlOrder.SelectedValue);
            moduleControl.ControlHeader = chkControlHeader.Checked;
            string roleList = "|";
            foreach (ListItem item in chkControlType.Items)
            {
                if (item.Selected)
                    roleList += item.Value + "|";
            }
            if (roleList.Length < 2) roleList = string.Empty;
            moduleControl.ControlTitle = txtControlTitle.Text;
            moduleControl.ControlRole = roleList;
            moduleControl.ControlDescription = txtControlDescription.Text.Trim();
            try
            {
                ModuleControlController.AddModuleControl(moduleControl);
                lblUpdateStatus.Text = MiscUtility.MSG_UPDATE_SUCCESS;
            }
            catch (Exception ex)
            {
                lblUpdateStatus.Text = ex.Message;
            }
            int moduleID = Convert.ToInt32(drgModules.SelectedValue);
            LoadForTreeView(moduleID);
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            string old_cmd = txtControlKey.Value;
            string new_cmd = MiscUtility.CreateCommand();
            while (ModuleControlController.CheckExistsControlKey(new_cmd))
            {
                new_cmd = MiscUtility.CreateCommand();
            }
            ModuleControlInfo moduleControl = new ModuleControlInfo();
            moduleControl.ControlID = Convert.ToInt32(txtID.Text);
            moduleControl.ModuleID = Convert.ToInt32(drgModules.SelectedValue);
            moduleControl.ControlName = txtControlName.Text.Trim();
            moduleControl.ControlKey = new_cmd;
            moduleControl.ControlPath = dropPath.SelectedValue;
            moduleControl.ControlIcon = txtControlIcon.Text.Trim();
            moduleControl.ControlOrder = ConvertUtility.ToInt32(dropControlOrder.SelectedValue);
            string roleList = "|";
            foreach (ListItem item in chkControlType.Items)
            {
                if (item.Selected)
                    roleList += item.Value + "|";
            }
            if (roleList.Length < 2) roleList = string.Empty;
            moduleControl.ControlRole = roleList;
            moduleControl.ControlTitle = txtControlTitle.Text;
            moduleControl.ControlDescription = txtControlDescription.Text;
            moduleControl.ControlHeader = chkControlHeader.Checked;
            try
            {
                ModuleControlController.UpdateModuleControl(moduleControl);
                CommandController.UpdateCommandbyControl(old_cmd, new_cmd);
                lblUpdateStatus.Text = MiscUtility.MSG_UPDATE_SUCCESS;
            }
            catch (Exception ex)
            {
                lblUpdateStatus.Text = ex.Message;
            }
            int moduleID = Convert.ToInt32(drgModules.SelectedValue);
            LoadForTreeView(moduleID);
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(txtID.Text) || Convert.ToInt32(txtID.Text) == 0)            
                lblUpdateStatus.Text = MiscUtility.MSG_UPDATE_ERROR;
            else
            {
                try
                {
                    ModuleControlController.DeleteModuleControl(Convert.ToInt32(txtID.Text));
                    lblUpdateStatus.Text = MiscUtility.MSG_UPDATE_SUCCESS;
                }
                catch (Exception ex)
                {
                    lblUpdateStatus.Text = ex.Message;
                }
                int moduleID = Convert.ToInt32(drgModules.SelectedValue);
                LoadForTreeView(moduleID);
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            this.txtControlDescription.Text = string.Empty;
            this.txtControlIcon.Text = string.Empty;
            this.txtControlName.Text = string.Empty;
            dropPath.SelectedIndex = -1;
            dropControlOrder.SelectedIndex = -1;
            this.txtControlTitle.Text = string.Empty;
        }

        protected void drgModules_SelectedIndexChanged(object sender, EventArgs e)
        {
            int moduleID = Convert.ToInt32(drgModules.SelectedValue);
            LoadForTreeView(moduleID);
            ModuleInfo module = ModuleController.GetModule(moduleID);
            if (module != null)
            {
                lblModuleName.Text = module.ModuleName;
                txtControlIcon.fpUploadDir = CheckPath(module);
                GetFiles(Server.MapPath("/"), Server.MapPath(module.ModuleFolder));
                dropPath.DataSource = lstFile;
                dropPath.DataBind();
            }
        }

        private string CheckPath(ModuleInfo module)
        {
            string temp = "/Uploads";           
            if (!Directory.Exists(Server.MapPath(temp)))
            {
                try
                {
                    Directory.CreateDirectory(Server.MapPath(temp));
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                    return "/Uploads";
                }
            }
            return temp;
        }

        private void GetFiles(string rootPath, string path)
        {
            string[] files = Directory.GetFiles(path);
            for (int i = 0; i < files.Length; i++)
            {
                if (files[i].EndsWith(".ascx"))
                {
                    string temp = files[i].Replace(rootPath, string.Empty);
                    temp = temp.Replace("\\", "/");
                    if (!temp.StartsWith("/")) temp = "/" + temp;
                    lstFile.Add(temp);
                }
            }
            string[] folders = Directory.GetDirectories(path);
            for (int i = 0; i < folders.Length; i++)
            {
                if (folders[i] == Server.MapPath("/Modules")) continue;
                if (folders[i] == Server.MapPath("/RadControls")) continue;
                if (folders[i] == Server.MapPath("/Themes")) continue;
                if (folders[i] == Server.MapPath("/Layouts")) continue;
                GetFiles(rootPath, folders[i]);
            }
            lstFile.Sort();
        }
	}
}